/* 9. 修改读者信息 */
const CHECK = require("../myUtil/formatCheck");
const db = require("../../coSqlite3");
const HTM = require("../myUtil/lib").html;

exports.updateUser = function* (req, res) {
    console.log("----------------------9. 修改读者信息\n");
    let rID = req.body.rID;
    let rName = req.body.rName;
    let rSex = req.body.rSex;
    let rDept = req.body.rDept;
    let rGrade = req.body.rGrade;


    let htm = HTM.divBegin + 2 + HTM.divEnd + '提交的参数有误: ';
    if (rID == '') {
        return HTM.begin + htm + '证号不能为空' + HTM.end;
    } else if (rID.length > 8) {
        return HTM.begin + htm + '证号长度不能超过8' + HTM.end;
    }

    if (rName.length > 10) {
        return HTM.begin + htm + '姓名长度不能超过10' + HTM.end;
    }

    if ('' != rSex && !(rSex == '男' || rSex == '女')) {
        return HTM.begin + htm + '请填写男或女' + HTM.end;
    }

    if (rDept.length > 10) {
        return HTM.begin + htm + '系名长度不能超过30' + HTM.end;
    }

    if ("" != rGrade && CHECK.isNotPositiveInt(rGrade)) {
      return HTM.begin + htm + "请填写正整数" + HTM.end;
    }


    let array = [rName, rSex, rDept, rGrade, rID];
    let args = [rID];
    let trueORFalse = [];
    for (let item of array) {
      if (item != "") {
        trueORFalse.push(true);
        args.push(item);
        continue;
      }
      trueORFalse.push(false);
    }

    let rows;
    htm = HTM.divBegin + 1 + HTM.divEnd;
    try {
        let exist = yield db.execSQL("SELECT count(rid) as count FROM reader WHERE rid = ?", [rID]);
        if (exist[0].count <= 0) {
            return HTM.begin + htm + '该证号不存在' + HTM.end;
        }
        rows = yield db.execSQL("update reader set rid = ?" +
            trueORFalse[0] ? ", rname = ?" : "" +
            trueORFalse[1] ? ", rsex = ?" : "" +
            trueORFalse[2] ? ", rdept= ?" : "" +
            trueORFalse[3] ? ", rgrade = ?" : "" +
            "where rid =? ", args);
    } catch (err) {
        htm = HTM.divBegin + 3 + HTM.divEnd + '数据库执行失败: ';
        return HTM.begin + htm + err + HTM.end;
    }

    htm = HTM.divBegin + 0 + HTM.divEnd;

    return HTM.begin + htm + '成功' + HTM.end;
}